var http = require('http');
var fs = require('fs');
var url = require('url');
var buf = new Buffer(11024);

//挂载服务器

http.createServer(function(rq, rs) {

  var page = url.parse(rq.url).pathname;
  // console.log(page);

  fs.readFile(page.substr(1), function(err, data) {
    if (err) {
      console.log("出错了：" + err);
      rs.writeHead(404, {
        'Content-Type': 'text/html'
      });
      fs.open('err.html', 'r+', function(err, fd) {
          fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {
            // rs.write()
            // var cs = buf.slice(0, bytes).toString()
            if (bytes > 0) {
              console.log(buf.slice(0, bytes).toString());
              rs.write(buf.slice(0, bytes).toString());
            }
            rs.end();
            // console.log(cs);
          })
        })
        // rs.write("./err.html");
    } else {
      rs.writeHead(200, {
        'Content-Type': 'text/html'
      })
      console.log(data);
      rs.write(data.toString());

      rs.end();
    }
  });
  // rs.write(" " + patname);
  // rs.end();
}).listen(8081);
